document.addEventListener('DOMContentLoaded', function() {
    // 如果已登录，则跳转到主页
    if (isLoggedIn()) {
        // window.location.href = 'home.html';
    }

    // 选项卡切换
    const tabs = document.querySelectorAll('.tab');
    const forms = document.querySelectorAll('.login-form');

    tabs.forEach(tab => {
        tab.addEventListener('click', function() {
            const tabType = this.getAttribute('data-tab');

            // 更新选项卡状态
            tabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');

            // 显示对应的表单
            forms.forEach(form => {
                form.classList.remove('active');
                if (form.id === `${tabType}-login`) {
                    form.classList.add('active');
                }
            });
        });
    });

    // 获取验证码功能
    const getPhoneCodeBtn = document.getElementById('get-phone-code');
    const getEmailCodeBtn = document.getElementById('get-email-code');

    function startCountdown(button) {
        let countdown = 60;
        button.disabled = true;
        button.textContent = `${countdown}秒后重新获取`;

        const timer = setInterval(() => {
            countdown--;
            button.textContent = `${countdown}秒后重新获取`;

            if (countdown <= 0) {
                clearInterval(timer);
                button.disabled = false;
                button.textContent = '获取验证码';
            }
        }, 1000);
    }

    // 发送验证码请求
    async function sendVerificationCode(type, target, codeType) {
        const url = type === 'phone' ?
            getApiUrl('/api/auth/sendPhoneCode') :
            getApiUrl('/api/auth/sendEmailCode');

        const data = type === 'phone' ?
            { phone: target, type: codeType } :
            { toEmail: target, type: codeType };

        const result = await apiPostJson(url, data);

        if (result.success) {
            showMessage('验证码发送成功', 'success');
            return true;
        } else {
            showMessage(result.message || '验证码发送失败', 'error');
            return false;
        }
    }

    if (getPhoneCodeBtn) {
        getPhoneCodeBtn.addEventListener('click', async function() {
            const phoneInput = document.getElementById('phone');
            if (!phoneInput.value) {
                showMessage('请输入手机号', 'error');
                return;
            }

            const success = await sendVerificationCode('phone', phoneInput.value, 2); // 2代表登录验证码
            if (success) {
                startCountdown(this);
            }
        });
    }

    if (getEmailCodeBtn) {
        getEmailCodeBtn.addEventListener('click', async function() {
            const emailInput = document.getElementById('email');
            if (!emailInput.value) {
                showMessage('请输入邮箱', 'error');
                return;
            }

            const success = await sendVerificationCode('email', emailInput.value, 2); // 2代表登录验证码
            if (success) {
                startCountdown(this);
            }
        });
    }

    // 表单提交
    const loginForms = document.querySelectorAll('.login-form');
    loginForms.forEach(form => {
        form.addEventListener('submit', async function(e) {
            e.preventDefault();

            let url, data;

            if (form.id === 'phone-login') {
                const phone = document.getElementById('phone').value;
                const code = document.getElementById('phone-code').value;

                if (!phone || !code) {
                    showMessage('请填写手机号和验证码', 'error');
                    return;
                }

                url = getApiUrl('/api/auth/login_phone');
                data = { phone, code };
            }
            else if (form.id === 'password-login') {
                const username = document.getElementById('username').value;
                const password = document.getElementById('password').value;

                if (!username || !password) {
                    showMessage('请填写用户名和密码', 'error');
                    return;
                }

                url = getApiUrl('/api/auth/login_pwd');
                data = { username, password };
            }
            else if (form.id === 'email-login') {
                const email = document.getElementById('email').value;
                const code = document.getElementById('email-code').value;

                if (!email || !code) {
                    showMessage('请填写邮箱和验证码', 'error');
                    return;
                }

                url = getApiUrl('/api/auth/login_email');
                data = { email, code };
            }

            const result = await apiPostForm(url, data);

            if (result.success) {
                // 保存token
                if (result.data && result.data.token) {
                    saveToken(result.data.token);
                }

                showMessage('登录成功', 'success');

                // 登录成功后跳转到主页
                setTimeout(() => {
                    // window.location.href = 'home.html';
                    console.log('登录成功，token已保存:', getToken());
                }, 1500);
            } else {
                showMessage(result.message || '登录失败', 'error');
            }
        });
    });

    // 显示消息
    function showMessage(message, type) {
        // 移除已存在的消息
        const existingMessage = document.querySelector('.message');
        if (existingMessage) {
            existingMessage.remove();
        }

        // 创建新消息
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.textContent = message;

        // 插入到表单前
        const activeForm = document.querySelector('.login-form.active');
        activeForm.insertBefore(messageDiv, activeForm.firstChild);

        // 3秒后自动消失
        setTimeout(() => {
            messageDiv.remove();
        }, 3000);
    }
});